<template>
  <div id="campusAreaDiv">
    <Breadcrumb content="采样类型" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="30">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getSampleTypeList" @keyup="keyupEnter" @search-click="getSampleTypeList()"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="tloading" @click="getSampleTypeList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addCallType()"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="handleSave"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteSampleType"></vxe-button>

            </template>
          </vxe-toolbar>

          <div class="tableBody">
            <vxe-table ref="campusAreaTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :data="sampleTypeList" :loading="tloading" @current-change="rowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: false, showIcon: false }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30px" align="center"></vxe-column>
              <vxe-column title="编码" field="sampleTypeCode" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                  <vxe-input v-model="row.sampleTypeCode" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column title="名称" field="sampleTypeName" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                  <vxe-input v-model="row.sampleTypeName" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column title="顺序" field="seq" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row }">
                  <vxe-input v-model="row.seq" type="text"></vxe-input>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <!-- 右侧项目信息 -->
        <Pane size="70">
          <Splitpanes horizontal>
            <Pane size="50">
              <Splitpanes>
                <pane size="50">
                  <vxe-toolbar perfect>
                    <template #buttons>
                      <div class="msgDiv">双击项目移除对应关系</div>
                    </template>
                  </vxe-toolbar>
                  <div class="feeTable">
                    <vxe-table ref="sampleTypeTable"  height="auto"  border resizable class="mytable-scrollbar" show-header-overflow show-overflow align="center" :row-config="{ isCurrent: true, isHover: true }" @cell-dblclick="deleteSampleCode" :data="sampleVsSampleItmeList" :loading="showLoading">
                      <vxe-column type="seq" title="序号" width="30"></vxe-column>
                      <vxe-column field="code" title="样本类型编号"  align="left"></vxe-column>
                      <vxe-column field="name" title="样本类型名称"  align="left"></vxe-column>
                      <vxe-column field="type" title="类型" width="150">
                        <template #default="{ row }">
                       {{row.type == '1' ? '样本' : '申请项目'}}
                        </template>
                      </vxe-column>
                    </vxe-table>
                  </div>
                </pane>
                <Pane size="50">
                  <vxe-toolbar perfect>
                    <template #buttons>
                      <vxe-input v-model="SampleTypeSearchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getSamItemList" @keyup="getSamItemList" @search-click="getSamItemList()"></vxe-input>
                      <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="getSamItemList"></vxe-button>
                      <div class="msgDiv">双击项目添加对应关系</div>
                    </template>
                  </vxe-toolbar>
                  <div class="feeTable">
                    <vxe-table ref="labFeeItemTable" height="auto" border class="mytable-scrollbar" show-header-overflow show-overflow align="left" :row-config="{ isCurrent: true, isHover: true }" @cell-dblclick="barCodeRowClick" :data="SampleTypes" :loading="showLoading">
                      <vxe-column type="seq" title="序号" width="30"></vxe-column>
                      <vxe-column field="sampleTypeCode" title="样本类型编号" width="60" align="left"></vxe-column>
                      <vxe-column field="sampleTypeName" title="样本类型名称" min-width="120" align="left"></vxe-column>
                      <vxe-column field="inputCode" title="助记符" width="65"></vxe-column>
                    </vxe-table>
                  </div>
                </Pane>
              </Splitpanes>
            </Pane>
            <Pane size="50">
              <Splitpanes>
                <pane size="50">
                  <div class="feeTable">
                    <vxe-table ref="feeItemVsBarCodeTable"  height="auto"  border resizable class="mytable-scrollbar" show-header-overflow show-overflow align="center" :row-config="{ isCurrent: true, isHover: true }" @cell-dblclick="deleteFeeCode" :data="SampleVsfeeItemList" :loading="showLoading">
                      <vxe-column type="seq" title="序号" width="30"></vxe-column>
                      <vxe-column field="code" title="申请项目编号"  align="left"></vxe-column>
                      <vxe-column field="name" title="申请项目名称"  align="left"></vxe-column>
                      <vxe-column field="type" title="类型" width="150">
                        <template #default="{ row }">
                          {{row.type == '1' ? '样本' : '申请项目'}}
                        </template>
                      </vxe-column>
                    </vxe-table>
                  </div>
                </pane>
                <Pane size="50">
                  <vxe-toolbar perfect>
                    <template #buttons>
                      <vxe-input v-model="FeeItemSearchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getFeeItemList" @keyup="getFeeItemList" @search-click="getFeeItemList()"></vxe-input>
                      <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="getFeeItemList"></vxe-button>
                    </template>
                  </vxe-toolbar>
                  <div class="feeTable">
                    <vxe-table ref="labFeeItemTable"  height="auto"  border class="mytable-scrollbar" show-header-overflow show-overflow align="left" :row-config="{ isCurrent: true, isHover: true }" @cell-dblclick="feeItemrowClick" :data="FeeItemList" :loading="showLoading">
                      <vxe-column type="seq" title="序号" width="30"></vxe-column>
                      <vxe-column field="feeCode" title="项目编号" width="60" align="left"></vxe-column>
                      <vxe-column field="feeName" title="项目名称" min-width="120" align="left"></vxe-column>
                      <vxe-column field="shortName" title="项目简称" width="65"></vxe-column>
                      <vxe-column field="price" title="单价" align="right" width="60"></vxe-column>
                    </vxe-table>
                  </div>
                </Pane>
              </Splitpanes>
            </Pane>
          </Splitpanes>
        </Pane>

      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import Breadcrumb from '@/components/Breadcrumb.vue';
import { isEmpty } from 'lodash';

let FeeItemList = reactive([]);
let SampleTypes = reactive([]);
const SampleVsfeeItemList = reactive([]);
const sampleVsSampleItmeList = reactive([]);
let showLoading = ref(false); //刷新+表格加载
let searchValue = ref('');
let FeeItemSearchValue = ref('');
let SampleTypeSearchValue = ref('');

let searchForm = {
  searchValue: ''
};
let tloading = ref(false); //加载状态
let sampleTypeList: any = reactive([
  {
    sampleTypeCode: '001',
    sampleTypeName: '抽血',
    seq:1
  }, {
    sampleTypeCode: '002',
    sampleTypeName: '验尿',
    seq:2
  }
]);
let sltCampusArea: any = reactive({});

let campusAreaForm = reactive({
  id: null,
  sampleTypeCode: '' /*编码*/,
  sampleTypeName: '' /*名称*/,
  seq: 1 /*显示顺序*/
});
onMounted(() => {
  getFeeItemList();
  getSamItemList();
  getSampleTypeList();
});

// 获取样本类型集合
function getSamItemList() {
  SampleTypes.length = 0;
  const url = '/api/lab/labSampleType/findSampleTypeList';
  let obj = {
    keyWords: SampleTypeSearchValue.value
  };
  proxy.$http
      .get(url, { params: obj })
      .then((res: any) => {
        SampleTypes.length = 0;
        Object.assign(SampleTypes, res.data);
        //SampleTypes.push(...res.data);
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
}

//双击新增样本类型
function barCodeRowClick({ row }: any) {
  const url = '/callNum/sampleVsFeeOrSam/addSampleTypeCode';
  let addSampleTypeCode = {
    sampleTypeCode: sltCampusArea.sampleTypeCode,
    code: row.sampleTypeCode,
    type: '1',
    seq: sampleVsSampleItmeList.length + 1
  };
  proxy.$http
      .post(url, addSampleTypeCode)
      .then((res: any) => {
        getSamDataList();
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
}
// 删除数据
function deleteSampleCode({ row }: any) {
  const url = '/callNum/sampleVsFeeOrSam/deleteSampleCode';
  proxy.$http
      .post(url, {
        id: row.id
      })
      .then((res: any) => {
        getSamDataList();
        VxeMessage(res.status.msg, VxeNotifyType.success);
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
}
// 获取样本类型集合
function getSamDataList() {
  sampleVsSampleItmeList.length = 0;
  const url = '/callNum/sampleVsFeeOrSam/getItemList';
  let obj = {
    sampleTypeCode: sltCampusArea.sampleTypeCode,
    type: '1',
  };
  proxy.$http
      .get(url, { params: obj })
      .then((res: any) => {
        sampleVsSampleItmeList.length = 0;
        Object.assign(sampleVsSampleItmeList, res.data);
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
}
//双击申请项目
function feeItemrowClick({ row }: any) {
  const url = '/callNum/sampleVsFeeOrSam/addSampleTypeCode';
  let addSampleTypeCode = {
    sampleTypeCode: sltCampusArea.sampleTypeCode,
    code: row.feeCode,
    type: '2',
    seq: SampleVsfeeItemList.length + 1
  };
  proxy.$http
      .post(url, addSampleTypeCode)
      .then((res: any) => {
        getFeeItmeDataList();
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
}

// 删除数据
function deleteFeeCode({ row }: any) {
  const url = '/callNum/sampleVsFeeOrSam/deleteSampleCode';
  proxy.$http
      .post(url, {
        id: row.id
      })
      .then((res: any) => {
        getFeeItmeDataList();
        VxeMessage(res.status.msg, VxeNotifyType.success);
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
}
// 获取样本类型集合
function getFeeItmeDataList() {
  SampleVsfeeItemList.length = 0;
  const url = '/callNum/sampleVsFeeOrSam/getItemList';
  let obj = {
    sampleTypeCode: sltCampusArea.sampleTypeCode,
    type: '2',
  };
  proxy.$http
      .get(url, { params: obj })
      .then((res: any) => {
        SampleVsfeeItemList.length = 0;
        Object.assign(SampleVsfeeItemList, res.data);
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
}

// 获取申请项目列表
function getFeeItemList() {
  FeeItemList.length = 0;
  const url = '/lis/fee/item/findFeeItemList';
  let obj = {
    keyWords: FeeItemSearchValue.value
  };
  proxy.$http
      .get(url, { params: obj })
      .then((res: any) => {
        FeeItemList.length = 0;
        Object.assign(FeeItemList, res.data);
        //FeeItemList.push(...res.data);
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
}

function getSampleTypeList() {
  tloading.value = true;
  sampleTypeList.length = 0; //放入数据前清空数据
  const url = '/callNum/sampleType/findSampleTypeList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchForm.searchValue
      }
    })
    .then((res: any) => {
      sampleTypeList.push(...res.data);
      const kn = sampleTypeList.find((k) => k.id == sltCampusArea.id);
      if (isEmpty(kn)) {
        rowClick({ row: sampleTypeList[0] }); //默认选中第一条数据
      } else {
        rowClick({ row: kn }); //默认选中第一条数据
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}
function deleteSampleType() {
  const sltCampusAreas = (proxy.$refs.campusAreaTableRef as any).getCheckboxRecords();
  if (!(sltCampusAreas.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delCampusAreaList = sltCampusAreas.filter((p: any) => !isEmpty(p.id));
        if (delCampusAreaList.length > 0) {
          const url = '/callNum/sampleType/batchDeleteSampleType';
          proxy.$http
            .post(url, delCampusAreaList)
            .then((res: any) => {
              getSampleTypeList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}
// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    getSampleTypeList();
  }
}
// 点击设计模式表格当前行触发右侧表单变化
function rowClick({ row }: any) {
  (proxy.$refs.campusAreaTableRef as any).setCurrentRow(row);
  sltCampusArea=row;
  proxy.$nextTick(() => {
    getSamDataList();
    getFeeItmeDataList();
  });

}
//新增
function addCallType() {
  const $table = proxy.$refs.campusAreaTableRef as any;
  const newRec = {
    // ref: ''
  } as any;

  sampleTypeList.push(newRec);
  $table.reloadData(sampleTypeList);
  $table.setEditRow(newRec);
  proxy.$nextTick(() => {
    setTimeout(() => {
      $table.scrollToRow(newRec);
    }, 50);
  });
}

// 保存
async function handleSave() {
  let $Xtable = proxy.$refs.campusAreaTableRef;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id && p.id !== '';
    });
    // 拿到数组中没有id的数据为新增
    const InsertRecords = sampleTypeList.filter((e: any) => {
      return !e.id || e.id === '';
    });

    const sampleResultList = [] as any[];
    updateRecords.forEach((e: any) => {
      const maItem = {
        id: e.id,
        sampleTypeCode: e.sampleTypeCode,
        sampleTypeName: e.sampleTypeName,
        seq: e.seq,
        orgId: e.orgId
      };
      sampleResultList.push(maItem);
    });
    InsertRecords.forEach((e: any) => {
      const maItem = {
        id: e.id,
        sampleTypeCode: e.sampleTypeCode,
        sampleTypeName: e.sampleTypeName,
        seq: e.seq,
        orgId: e.orgId
      };
      sampleResultList.push(maItem);
    });

    if (sampleResultList.length > 0) {
      const url = '/callNum/sampleType/saveOrUpdateSampleType';
      proxy.$http
          .post(url, sampleResultList)
          .then((res: any) => {
            VxeMessage('修改成功', VxeNotifyType.success);
            setTimeout(() => {
              getSampleTypeList();
            }, 500);
          })
          .catch((err: any) => {
            VxeMessage('修改失败', VxeNotifyType.success);
          });
    } else {
      VxeMessage('无添加或修改数据', VxeNotifyType.error);
    }
  } else {
    return;
  }

}


// 清空中间规则弹框表单
function clearForm() {
  for (let key in campusAreaForm) {
    campusAreaForm[key] = '';
  }
  campusAreaForm.id = null;
  campusAreaForm.seq = 1;
}

</script>

<style lang="scss" scoped>
#campusAreaDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .tableBody {
        height: calc(100% - 40px - 32px);
      }
      .feeTable{
        height: calc(100%);
      }
      .el-tabs {
        height: 100%;
        :deep(.el-tabs__content) {
          height: calc(100% - 40px - 30px);
          .el-tab-pane {
            height: 100%;
          }
        }
      }
    }
  }
}
</style>